package com.example.rule.action;


import com.example.rule.core.Action;
import com.example.rule.core.Facts;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.math.BigDecimal;

/**
 * @author Jason - Chusifeng
 * @version 1.0.0
 * @ClassName RateAction.java
 * @PackageName com\welab\vb\payment\transaction\rule\action\RateAction.java
 * @Description 直接指定费率计算的执行action
 * @createTime 2022年10月10日 11:04:11
 */
public class RateAction implements Action {
    private final StandardEvaluationContext context = new StandardEvaluationContext();
    private final ExpressionParser parser = new SpelExpressionParser();
    private final Expression compiledExpression;

    private double rate;

    public RateAction(String expression) {
        compiledExpression = parser.parseExpression(expression);
    }

    @Override
    public BigDecimal execute(Facts facts) throws Exception {
        context.setVariables(facts.asMap());
        context.setRootObject(facts.asMap());
        return compiledExpression.getValue(context, BigDecimal.class);

    }
}
